﻿using System;
using System.Net;
using ApiGateway.Config;
using ApiGateway.Interface;
using RpcCacheClient.Interface;
using RpcHelper;

namespace ApiGateway.IpLimit
{
    internal class RemoteIpLimit : IIpLimit
    {
        private int _LimitNum;
        private int _LimitTime;
        private readonly string _CacheKey;
        private readonly IRedisCache _Cache;
        private int _Heartbeat = 0;
        public RemoteIpLimit(string ip, IpLimitConfig limit, IRedisCache cache)
        {
            this.Ip = ip;
            this._Cache = cache;
            this._Heartbeat = HeartbeatTimeHelper.HeartbeatTime;
            this._CacheKey = string.Concat("IpLimit_", IPAddress.Parse(ip).Address);
            this._LimitNum = limit.LimitNum;
            this._LimitTime = limit.LimitTime;
        }
        public string Ip { get; }

        public bool IsLimit()
        {
            long num = this._Cache.Increment(this._CacheKey, 1);
            if (num == 1)
            {
                _ = this._Cache.SetExpire(this._CacheKey, DateTime.Now.AddSeconds(this._LimitTime));
            }
            this._Heartbeat = HeartbeatTimeHelper.HeartbeatTime;
            return num > this._LimitNum;
        }

        public int Refresh(int now)
        {
            return this._Heartbeat;
        }
        public void Reset(IpLimitConfig config)
        {
            this._LimitNum = config.LimitNum;
            this._LimitTime = config.LimitTime;
        }
    }
}
